package logic

import (
	"context"
	"fmt"
	"math/rand"
	"shopping-mall/models"
	"shopping-mall/shopping_rpc/shopping_rpc"
	"time"

	"shopping-mall/shopping_rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SmsCaptchaLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSmsCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SmsCaptchaLogic {
	return &SmsCaptchaLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SmsCaptchaLogic) SmsCaptcha(in *shopping_rpc.SmsCaptchaRequest) (*shopping_rpc.SmsCaptchaResponse, error) {
	// todo: add your logic here and delete this line

	key := fmt.Sprintf("%s:%s", in.From, in.Phone)
	code := fmt.Sprintf("%d", rand.Intn(9000)+1000)
	fmt.Println(1)
	MinGet, _ := models.RDB.Get(models.Ctx, key+"MinCon").Result()
	if MinGet != "" {
		return &shopping_rpc.SmsCaptchaResponse{}, fmt.Errorf("一分钟内仅可发送一条短信")
	}
	HorGet, _ := models.RDB.Get(models.Ctx, key).Int()
	fmt.Println(HorGet)
	if HorGet >= 10 {
		return &shopping_rpc.SmsCaptchaResponse{}, fmt.Errorf("一小时内仅可发送十条短信")
	}
	//sms, err := pkg.Sms(code, in.Phone)
	//if err != nil {
	//	return nil, err
	//}
	//if *sms.Body.Code != "OK" {
	//	return nil, fmt.Errorf(*sms.Body.Message)
	//}
	models.RDB.Set(models.Ctx, key, code, 5*time.Minute)
	models.RDB.Set(models.Ctx, key+"MinCon", "count", 1*time.Minute)
	models.RDB.Incr(models.Ctx, key+"HorCon")
	if HorGet == 0 {
		models.RDB.Expire(models.Ctx, key+"HorCon", 1*time.Hour)
	}
	return &shopping_rpc.SmsCaptchaResponse{}, nil
}
